#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <pthread.h>
#include <fcntl.h> 
#include <time.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/msg.h>
#include <sys/ipc.h> 
#include <sys/select.h>    
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/prctl.h>
#include <net/if.h>

#include <netinet/in.h>
#include <arpa/inet.h>

#include <sys/reboot.h>


#define SIZE_MAC                    8      

#define IPC_DBG printf
int eth_get_mac(const char *inf)
{
    struct ifreq ifr;
    int sd;
    int i;
	char mac[20] = {0};

    bzero(&ifr, sizeof(struct ifreq));
    if((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        IPC_DBG("get %s mac address socket creat error\n", inf);
        return -1;
    }

    strncpy(ifr.ifr_name, inf, sizeof(ifr.ifr_name) - 1);

    if(ioctl(sd, SIOCGIFHWADDR, &ifr) < 0)
    {
        IPC_DBG("get %s mac address error\n", inf);
        close(sd);
        return -1;
    }
    /*
	memset((unsigned char*)ifr.ifr_hwaddr.sa_data, 0, SIZE_MAC);
	memcpy((unsigned char*)ifr.ifr_hwaddr.sa_data,(unsigned char*)ifr.ifr_hwaddr.sa_data, 6);*/
    snprintf(mac, 18, "%02x:%02x:%02x:%02x:%02x:%02x",
            ifr.ifr_hwaddr.sa_data[0],
            ifr.ifr_hwaddr.sa_data[1],
            ifr.ifr_hwaddr.sa_data[2],
            ifr.ifr_hwaddr.sa_data[3],
            ifr.ifr_hwaddr.sa_data[4],
            ifr.ifr_hwaddr.sa_data[5]);
    
    close(sd);

    for(i = 0; i < 18; i++)
    {
        if(mac[i]>='a'&&mac[i]<='z')
            mac[i]-=32;
    }
	IPC_DBG("get mac : %s \r\n", mac);
    return 0;
}


int eth_get_ipaddr(const char *ifname)
{
	struct ifreq ifr;
	int skfd = 0;
	char if_addr[16];

	if((skfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		return -1;
	}

	strncpy(ifr.ifr_name, ifname, IF_NAMESIZE);
	if (ioctl(skfd, SIOCGIFADDR, &ifr) < 0) {
		close(skfd);
		return -1;
	}
    memset(if_addr,0,sizeof(if_addr));
	strcpy(if_addr, inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));
	close(skfd);
	
	if(strlen(if_addr))
	{
        printf("get ip:%s\n",if_addr);
		return 0;
	}else{
		return -1;
	}
}


int main(int argc,char *argv[])
{
    int ret = -1;
    const char *inf= "eth3";
    if(argc == 2){
        IPC_DBG("%s\n",argv[1]);
        inf= argv[1];
    }
    ret = eth_get_mac(inf);
    if(ret){
        IPC_DBG("eth_get_mac err\n");
    }
    ret = eth_get_ipaddr(inf);
    if(ret){
        IPC_DBG("eth_get_ipaddr err\n");
    }
    return ret;

}